<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="manager">
        <el-input
          v-model="queryParams.manager"
          placeholder="请输入负责人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入版本号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['agent:manage-product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增产品
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="product-grid" v-loading="loading">
      <div v-for="product in list" :key="product.id" class="product-card">
        <div class="product-header">
          <Icon icon="ep:box" class="product-icon" />
          <div class="product-status">
            <div class="status-dot" :class="getStatusClass(product.status)"></div>
          </div>
        </div>

        <h3 class="product-name">{{ product.name }}</h3>
        <p class="product-description">{{ product.description }}</p>

        <div class="product-info">
          <div class="info-item">
            <span class="label">版本:</span>
            <span class="value">{{ product.version || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">负责人:</span>
            <span class="value">{{ product.manager || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">状态:</span>
            <span class="value">{{ product.status || '-' }}</span>
          </div>
        </div>

        <div class="product-categories">
          <div class="category-item" @click="openCategory(product, 'presale')">
            <Icon icon="ep:document" />
            <span>售前资料</span>
            <el-badge :value="product.presaleCount || 0" class="badge" />
          </div>
          <div class="category-item" @click="openCategory(product, 'acceptance')">
            <Icon icon="ep:check" />
            <span>验收资料</span>
            <el-badge :value="product.acceptanceCount || 0" class="badge" />
          </div>
          <div class="category-item" @click="openCategory(product, 'technical')">
            <Icon icon="ep:cpu" />
            <span>产品技术</span>
            <el-badge :value="product.technicalCount || 0" class="badge" />
          </div>
          <div class="category-item" @click="openCategory(product, 'other')">
            <Icon icon="ep:more-filled" />
            <span>其他</span>
            <el-badge :value="product.otherCount || 0" class="badge" />
          </div>
        </div>

        <div class="product-actions">
          <el-button type="primary" @click="viewProduct(product)">
            <Icon icon="ep:view" />查看详情
          </el-button>
          <el-button @click="editProduct(product)" v-hasPermi="['agent:manage-product:update']">
            <Icon icon="ep:edit" />编辑
          </el-button>
          <el-button
            type="danger"
            @click="deleteProduct(product.id)"
            v-hasPermi="['agent:manage-product:delete']"
          >
            <Icon icon="ep:delete" />删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 分类资料弹窗 -->
  <el-dialog v-model="showCategoryDialog" :title="categoryTitle" width="800px">
    <div class="category-content">
      <div class="category-header">
        <el-button type="primary" @click="showMaterialForm = true">
          <Icon icon="ep:plus" />添加资料
        </el-button>
      </div>
      
      <el-table :data="categoryMaterials" stripe>
        <el-table-column prop="name" label="资料名称" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="creator" label="创建用户" width="120" />
        <el-table-column prop="createTime" label="创建日期" width="120" :formatter="dateFormatter" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="downloadMaterial(row)">下载</el-button>
            <el-button size="small" type="danger" @click="deleteMaterial(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>

  <!-- 资料表单弹窗 -->
  <el-dialog v-model="showMaterialForm" title="添加资料" width="500px">
    <el-form :model="materialForm" label-width="80px">
      <el-form-item label="资料名称">
        <el-input v-model="materialForm.name" />
      </el-form-item>
      <el-form-item label="资料类型">
        <el-select v-model="materialForm.type">
          <el-option label="文档" value="word" />
          <el-option label="PDF" value="pdf" />
          <el-option label="Excel" value="excel" />
          <el-option label="PPT" value="ppt" />
          <el-option label="图片" value="image" />
          <el-option label="视频" value="video" />
          <el-option label="压缩包" value="zip" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="文件上传">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          multiple
        >
          <Icon icon="ep:upload-filled" size="40" />
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="版本">
        <el-input v-model="materialForm.version" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="materialForm.remark" type="textarea" :rows="2" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showMaterialForm = false">取消</el-button>
      <el-button type="primary" @click="saveMaterial">保存</el-button>
    </template>
  </el-dialog>

  <!-- 产品表单 -->
  <ProductForm ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ManageProductApi, type ManageProductVO } from '@/api/agent/manage/manageProduct'
import { MaterialApi, type MaterialVO } from '@/api/agent/manage/material'
import { dateFormatter } from '@/utils/formatTime'
import ProductForm from './ProductForm.vue'

defineOptions({ name: 'ProductManage' })

const router = useRouter()
const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<ManageProductVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 12,
  name: undefined,
  manager: undefined,
  version: undefined
})
const queryFormRef = ref()

// 分类相关
const showCategoryDialog = ref(false)
const currentCategory = ref('')
const currentProduct = ref<ManageProductVO | null>(null)
const categoryMaterials = ref<MaterialVO[]>([])

const categoryTitle = computed(() => {
  const titles = {
    presale: '售前资料',
    acceptance: '验收资料',
    technical: '产品技术',
    other: '其他资料'
  }
  return titles[currentCategory.value] || '资料管理'
})

// 资料表单
const showMaterialForm = ref(false)
const materialForm = ref<MaterialVO>({
  id: undefined,
  name: '',
  type: '',
  category: '',
  relatedId: 0,
  relatedType: 'product',
  size: '',
  version: '',
  fileUrl: '',
  remark: ''
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ManageProductApi.getManageProductPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 查看产品详情 */
const viewProduct = (product: ManageProductVO) => {
  router.push(`/agent/project-manage/product/detail/${product.id}`)
}

/** 编辑产品 */
const editProduct = (product: ManageProductVO) => {
  openForm('update', product.id)
}

/** 删除产品 */
const deleteProduct = async (id: number) => {
  try {
    await message.delConfirm()
    await ManageProductApi.deleteManageProduct(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除产品失败:', error)
  }
}

/** 获取状态样式类 */
const getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    '已发布': 'online',
    '开发中': 'development',
    '测试中': 'testing',
    '已下线': 'offline'
  }
  return classMap[status] || 'offline'
}

/** 打开分类资料 */
const openCategory = async (product: ManageProductVO, category: string) => {
  currentProduct.value = product
  currentCategory.value = category
  
  try {
    const params = {
      relatedId: product.id,
      relatedType: 'product',
      category: category
    }
    const data = await MaterialApi.getMaterialPage(params)
    categoryMaterials.value = data.list || []
  } catch (error) {
    console.error('获取资料列表失败:', error)
    categoryMaterials.value = []
  }
  
  showCategoryDialog.value = true
}

/** 保存资料 */
const saveMaterial = async () => {
  try {
    materialForm.value.category = currentCategory.value
    materialForm.value.relatedId = currentProduct.value?.id || 0
    materialForm.value.relatedType = 'product'
    
    await MaterialApi.createMaterial(materialForm.value)
    message.success('资料添加成功')
    showMaterialForm.value = false
    
    // 重新加载资料列表
    if (currentProduct.value) {
      openCategory(currentProduct.value, currentCategory.value)
    }
  } catch (error) {
    console.error('保存资料失败:', error)
  }
}

/** 下载资料 */
const downloadMaterial = (material: MaterialVO) => {
  if (material.fileUrl) {
    window.open(material.fileUrl, '_blank')
  } else {
    message.warning('文件地址不存在')
  }
}

/** 删除资料 */
const deleteMaterial = async (id: number) => {
  try {
    await message.delConfirm()
    await MaterialApi.deleteMaterial(id)
    message.success('删除成功')
    
    // 重新加载资料列表
    if (currentProduct.value) {
      openCategory(currentProduct.value, currentCategory.value)
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除资料失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.product-card {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 3px 15px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(229, 231, 235, 0.8);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  text-align: center;
  position: relative;
  overflow: hidden;
  height: auto;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover {
    transform: translateY(-6px) scale(1.01);
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.12);
    border-color: rgba(102, 126, 234, 0.3);
    
    &::before {
      opacity: 1;
    }
  }

  .product-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;
    position: relative;

    .product-icon {
      font-size: 48px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      margin: 0 auto;
      filter: drop-shadow(0 1px 3px rgba(102, 126, 234, 0.2));
    }

    .product-status {
      position: absolute;
      top: -6px;
      right: -6px;
      
      .status-dot {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        border: 2px solid white;
        box-shadow: 0 1px 6px rgba(0, 0, 0, 0.12);

        &.online {
          background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
          animation: pulse-green 2s infinite;
        }

        &.development {
          background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
          animation: pulse-blue 2s infinite;
        }

        &.testing {
          background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
          animation: pulse-orange 2s infinite;
        }

        &.offline {
          background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
          animation: pulse-red 2s infinite;
        }
      }
    }
  }

  .product-name {
    margin: 0 0 12px 0;
    color: #1f2937;
    font-size: 16px;
    font-weight: 700;
    letter-spacing: -0.025em;
    line-height: 1.3;
  }

  .product-description {
    color: #6b7280;
    margin-bottom: 16px;
    line-height: 1.5;
    text-align: left;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    font-size: 12px;
    background: rgba(249, 250, 251, 0.8);
    padding: 8px;
    border-radius: 6px;
    border-left: 2px solid #e5e7eb;
  }

  .product-info {
    margin-bottom: 16px;
    text-align: left;
    background: rgba(248, 250, 252, 0.6);
    padding: 12px;
    border-radius: 8px;
    border: 1px solid rgba(229, 231, 235, 0.6);

    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-size: 12px;
      padding: 4px 0;
      border-bottom: 1px solid rgba(229, 231, 235, 0.4);

      &:last-child {
        border-bottom: none;
        margin-bottom: 0;
      }

      .label {
        color: #6b7280;
        font-weight: 500;
        min-width: 60px;
        font-size: 11px;
      }

      .value {
        color: #1f2937;
        font-weight: 600;
        font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace;
        background: rgba(255, 255, 255, 0.8);
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 11px;
      }
    }
  }

  .product-categories {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-bottom: 16px;

    .category-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px;
      background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s ease;
      border: 1px solid rgba(203, 213, 225, 0.5);

      &:hover {
        background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
        transform: translateY(-1px);
        box-shadow: 0 3px 8px rgba(71, 85, 105, 0.15);
      }

      .el-icon {
        margin-right: 4px;
        color: #667eea;
        font-size: 14px;
      }
      
      span {
        font-size: 11px;
        font-weight: 500;
        color: #475569;
      }
      
      .badge {
        margin-left: auto;
      }
    }
  }

  .product-actions {
    display: flex;
    flex-direction: row;
    gap: 8px;

    .el-button {
      flex: 1;
      font-weight: 600;
      border-radius: 6px;
      padding: 8px 12px;
      transition: all 0.3s ease;
      font-size: 12px;
      
      &.el-button--primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        box-shadow: 0 3px 8px rgba(102, 126, 234, 0.3);
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.5);
        }
      }
      
      &.el-button--danger {
        background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
        border: none;
        color: white;
        box-shadow: 0 3px 8px rgba(245, 108, 108, 0.3);
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(245, 108, 108, 0.5);
        }
      }
      
      &:not(.el-button--primary):not(.el-button--danger) {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        border: 1px solid #cbd5e1;
        color: #475569;
        
        &:hover {
          background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(71, 85, 105, 0.15);
        }
      }
    }
  }
}

.category-content {
  .category-header {
    margin-bottom: 20px;
    text-align: right;
  }
}

@keyframes pulse-green {
  0%, 100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  }
  50% {
    box-shadow: 0 0 0 6px rgba(103, 194, 58, 0);
  }
}

@keyframes pulse-blue {
  0%, 100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
  }
  50% {
    box-shadow: 0 0 0 6px rgba(64, 158, 255, 0);
  }
}

@keyframes pulse-orange {
  0%, 100% {
    box-shadow: 0 0 0 0 rgba(230, 162, 60, 0.7);
  }
  50% {
    box-shadow: 0 0 0 6px rgba(230, 162, 60, 0);
  }
}

@keyframes pulse-red {
  0%, 100% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.7);
  }
  50% {
    box-shadow: 0 0 0 6px rgba(245, 108, 108, 0);
  }
}
</style>